package com.detrum.sportcamera.runnable;

import android.os.Handler;

import com.detrum.sportcamera.jlibrtp.DFrame;
import com.detrum.sportcamera.jlibrtp.FrameNode;
import com.detrum.sportcamera.jlibrtp.PktBuffer;
import com.detrum.sportcamera.jlibrtp.RtpPkt;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketTimeoutException;

/**
 * Created by abc on 2018/2/3.
 */

public class PreviewRunnable implements Runnable {
    private DatagramPacket outPacket;
    private DatagramSocket receiverSocket;
    private PktBuffer pktBuffer = new PktBuffer();
    private Handler handler;
    private PreviewCall previewCall;

    public PreviewRunnable(DatagramSocket receiverSocket,Handler handler,PreviewCall previewCall) {
        this.receiverSocket = receiverSocket;
        this.handler = handler;
        this.previewCall = previewCall;
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] receiveData = new byte[1024 * 10];
                outPacket = new DatagramPacket(receiveData, receiveData.length);
                if (receiverSocket != null && !receiverSocket.isClosed()) {
                    receiverSocket.receive(outPacket);
                } else {
                    return;
                }
                DFrame dFrame = new DFrame(outPacket.getData(), outPacket.getLength());
                RtpPkt rtpPkt = new RtpPkt(outPacket.getData(), 8, outPacket.getLength() - 8);
                int ret = pktBuffer.addPkt(rtpPkt);
                if (ret > 0) {
                    FrameNode frame = pktBuffer.popOldestFrame();
                    if (frame == null) {
                        return;
                    }
                    int est_frame_len = frame.getFrameEstLen();

                    byte[] frame_bytes = new byte[est_frame_len];
                    int len = frame.getData(frame_bytes, 0, frame_bytes.length);
                    //回调预览数据到Activity
                    previewCall.receiveData(frame_bytes,len);
                }
                outPacket = null;
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(100);
                break;
            } catch (IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(200);
                break;
            }
        }
    }
}
